package com.study.demo.components.storage;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

import com.study.demo.db.User;
import com.study.demo.service.MessageService;
import com.study.demo.util.SettingPrefUtil;

/**
 * Created by shangsong on 17-3-2.
 */

public class UserStorage {
    private final Context mContext;
    private User user;

    public UserStorage(Context mContext) {
        this.mContext = mContext;
    }

    public void login(User user) {
        this.user = user;
        SettingPrefUtil.setLoginUid(mContext, user.getUid());
        Intent intent = new Intent(mContext, MessageService.class);
        intent.setAction(MessageService.ACTION_GET);
        mContext.startService(intent);
    }

    public void logout() {
        if (TextUtils.equals(user.getUid(), SettingPrefUtil.getLoginUid(mContext))) {
            SettingPrefUtil.setLoginUid(mContext, "");
        }
        user = null;
        removeCookie();
        Intent intent = new Intent(mContext, MessageService.class);
        intent.setAction(MessageService.ACTION_CLOSE);
        mContext.startService(intent);
    }


    public boolean isLogin() {
        return user != null &&
                TextUtils.equals(SettingPrefUtil.getLoginUid(mContext), user.getUid());
    }

    private void removeCookie() {
        CookieSyncManager.createInstance(mContext);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        if (Build.VERSION.SDK_INT < 21) {
            CookieSyncManager.getInstance().sync();
        } else {
            cookieManager.flush();
        }
    }

    public String getToken() {
        if (isLogin()) {
            return user.getToken();
        } else {
            return "";
        }
    }

    public String getUid() {
        if (isLogin()) {
            return user.getUid();
        } else {
            return "";
        }
    }

    public String getCookie() {
        if (isLogin()) {
            return user.getCookie();
        }
        return "";
    }

    public User getUser() {
        return user;
    }

}
